package com.weds.frame.common.entity;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/28 10:26
 */
public class InputStreamHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public String body;

    private Map<String, String> headerMap = new HashMap<>();

    public String getBody() {
        return this.body;
    }

    public void addHeader(String name, String value) {
        headerMap.put(name, value);
    }

    public String getHeader(String name) {
        String headerValue = headerMap.get(name);

        if (headerValue != null) {
            return headerValue;
        }
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }

    public String getParameter(String key) {
        return ((HttpServletRequest) getRequest()).getParameter(key);
    }

    public InputStreamHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        request.setCharacterEncoding("UTF-8");
        if (request.getHeader("content-type") != null &&
                request.getHeader("content-type").contains("multipart/form-data")) {
            return;
        }
        StringBuffer sBuffer = new StringBuffer();
        BufferedReader bufferedReader = request.getReader();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sBuffer.append(line);
        }
        body = sBuffer.toString();
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {
            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

}
